package com.example.demo.security;


import com.example.demo.conf.Config;
import com.example.demo.domain.User;
import com.example.demo.util.JWTTokenUtil;
import com.example.demo.util.ParseUsername;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;

/**
 * token过滤器
 */
@Slf4j
public class JWTTokenFilter extends OncePerRequestFilter {
    @Qualifier("userDetailsServiceImpl")
    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private JWTTokenUtil jwtTokenUtil;

    @Override
    protected void doFilterInternal (HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {

//        System.out.println("token过滤器");
//        System.out.println(new Date());
        // 获取请求头中JWT的Token
//        log.info("用户{}发出了一个请求", ParseUsername.getUser());
        String authHeader = request.getHeader( Config.HEADER_STRING );
//        System.out.println(authHeader);
        if (authHeader != null && authHeader.startsWith( Config.TOKEN_PREFIX )) {
            // 截取JWT前缀
            final String authToken = authHeader.substring( Config.TOKEN_PREFIX.length() );
                // 解析JWT，获取用户名
                String username = jwtTokenUtil.getUsernameFromToken(authToken);
//                System.out.println("当前用户为:"+username);
                if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
//                    System.out.println("用户名不为空");
                    UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);
//                    User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
                    if (jwtTokenUtil.validateToken(authToken, userDetails)) {
//                        System.out.println("token验证通过");
                        // 组装参数
//                        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
//                                userDetails, userDetails.getUsername(), userDetails.getAuthorities());
                        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                                userDetails, userDetails.getPassword(), userDetails.getAuthorities());
                        authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(
                                request));
                        SecurityContextHolder.getContext().setAuthentication(authentication);
                        //TODO:刷新token
//                    if(jwtTokenUtil.canTokenBeRefreshed(authToken)){
//                        String refreshedToken = jwtTokenUtil.refreshToken(authToken);
//                    }
                    }
//                    else{
//                        System.out.println("当前请求的token与SecurityContextHolder中的用户信息不匹配");
//                        response.sendError(HttpStatus.BAD_REQUEST.value(), "请求认证失败");
//                        return;
//                    }
                }
        }
        else{
            System.out.println("请求头非法");
            response.sendError(HttpStatus.BAD_REQUEST.value(), "请求认证失败");
            return;
        }
//        System.out.println("Request URL is:"+request.getRequestURL());
//        System.out.println("Request Method is:"+request.getMethod());
        chain.doFilter(request, response);
//        System.out.println("Response Status Code is:"+response.getStatus());
    }
}
